package cn.ycc1.gateway;

import com.alibaba.fastjson.JSONObject;
import com.oracle.webservices.internal.api.message.BasePropertySet;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.neo4j.Neo4jProperties;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.ReactiveSecurityContextHolder;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.OAuth2Request;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.servlet.support.RequestContext;
import reactor.core.publisher.Mono;

import java.util.*;

/**
 * @Title:
 * @Author ycc
 * @Date 2023/7/6 8:08
 */
@Component
@Order(-1)
@Slf4j
public class AuthorizeFilter implements GlobalFilter {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        log.info("--------测试");
        ServerHttpRequest request = exchange.getRequest();
        MultiValueMap<String, String> params = request.getQueryParams();
        String authorization = params.getFirst("authorization");

        // 获取当前用户身份信息
        // 获取当前用户的权限信息
        // 把身份信息和权限信息放在json中，加入http的header中
        // 转发给微服务

        // 获取令牌内容
        // 从安全上下文中拿到用户的身份对象
        // Authentication authentication = ReactiveSecurityContextHolder.getContext().as(authorization);


//        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
//       // Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
//        if(!(authentication instanceof OAuth2Authentication)) {
//            // return null;
//            exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
//            return exchange.getResponse().setComplete();
//        }
//
//        OAuth2Authentication oAuth2Authentication = (OAuth2Authentication) authentication;
//        Authentication userAuthentication = oAuth2Authentication.getUserAuthentication();
//        // Object principalObj = userAuthentication.getPrincipal();
//        String principal = userAuthentication.getName();
//
//        /**
//         * 组装明文，转发给微服务，放入header,名称为json-token
//         */
//        List<String> authorities = new ArrayList<>();
//        userAuthentication.getAuthorities().stream().forEach(
//                s->authorities.add(
//                        ((GrantedAuthority) s).getAuthority()
//                )
//        );
//
//        OAuth2Request oAuth2Request = oAuth2Authentication.getOAuth2Request();
//        Map<String, String> requestParameters = oAuth2Request.getRequestParameters();
//        Map<String, Object> jsonToken = new HashMap<>(requestParameters);
//        if(userAuthentication != null) {
//            jsonToken.put("principal", principal);
//            jsonToken.put("authorities", authorities);
//        }
//
//        HttpHeaders headers = request.getHeaders();
//        byte[] jsonTokenValue = Base64.getEncoder().encode(JSONObject.toJSONString(jsonToken).getBytes());
//        headers.add("json-token", new String(jsonTokenValue)); // 添加自定义header

        return chain.filter(exchange);
//        if(authorization.equals("admin")) {
//            return chain.filter(exchange);
//        }
//
//        exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
//        return exchange.getResponse().setComplete();

    }
}
